<template>
  <div class="cart">
    <Header></Header>
    <div class="cart_info">
      <!-- 购物车标题 -->
      <div class="cart_title">
        <span class="text">我的购物车</span>
        <span class="total">共 {{ cart_length }} 门课程</span>
      </div>

      <!-- 购物车内容 -->
      <div class="cart_table">
        <!-- 顶部全选和操作栏 -->
        <div class="cart_head_row">
          <span class="select_all">
            <el-checkbox v-model="is_all_selected" @change="handle_select_all">全选</el-checkbox>
          </span>
          <span class="operation">
            <el-button type="text" @click="handle_delete_selected">删除选中</el-button>
          </span>
        </div>

        <!-- 商品列表 -->
        <div class="cart_course_list">
          <CartItem
              v-for="cart in cart_list"
              :cart="cart"
              :key="cart.id"
              @select-change="handle_select_change"
          ></CartItem>
        </div>

        <!-- 底部结算栏 -->
        <div class="cart_footer_row">
          <span class="select_all">
            <el-checkbox v-model="is_all_selected" @change="handle_select_all">全选</el-checkbox>
          </span>
          <span class="total_price">
            总计：<span class="price">¥{{ total_price.toFixed(2) }}</span>
          </span>
          <span class="goto_pay">
            <el-button type="danger" :disabled="selected_items.length === 0">去结算 ({{ selected_items.length }})</el-button>
          </span>
        </div>
      </div>
    </div>
    <Footer></Footer>
  </div>
</template>
<script>
import Header from "./common/Header";
import Footer from "./common/Footer";
import CartItem from "./common/Cartitem";


export default {
  name: "Cart",
  data() {
    return {
      cart_length: 0,
      cart_list: [],
      is_all_selected: false, // 是否全选
      selected_items: [], // 选中的商品
    };
  },
  computed: {
    // 计算总价
    total_price() {
      return this.selected_items.reduce((total, item) => total + item.price, 0);
    },
  },
  created() {
    this.token = this.check_user_login();
    this.get_cart();
  },
  methods: {
    // 检查用户是否登录
    check_user_login() {
      let token = localStorage.access || sessionStorage.access;
      if (!token) {
        let self = this;
        self.$confirm("您尚未登陆！请登陆后再添加购物车", "好课优选", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.$router.push('/user/login');
        });
        return false;
      }
      return token;
    },
    // 获取购物车数据
    get_cart() {
      this.$axios.get(`${this.$settings.HOST}/cart/`, {
        headers: {
          Authorization: `Bearer ${this.token}`
        },
      }).then((response) => {
        this.cart_list = response.data.data;
        this.cart_length = response.data.cart_length;
      }).catch(error => {
        console.error('获取购物车数据失败:', error);
      });
    },
    // 处理全选
    handle_select_all() {
      this.cart_list.forEach(item => {
        item.is_selected = this.is_all_selected;
      });
      this.update_selected_items();
    },
    // 处理单个商品选中状态变化
    handle_select_change(cart) {
      this.update_selected_items();
      this.is_all_selected = this.cart_list.every(item => item.is_selected);
    },
    // 更新选中的商品
    update_selected_items() {
      this.selected_items = this.cart_list.filter(item => item.is_selected);
    },
    // 删除选中的商品
    handle_delete_selected() {
      if (this.selected_items.length === 0) {
        this.$message.warning("请先选择要删除的商品");
        return;
      }
      this.$confirm("确定删除选中的商品吗？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const selected_ids = this.selected_items.map(item => item.id);
        this.$axios.delete(`${this.$settings.HOST}/cart/`, {
          data: { ids: selected_ids },
          headers: {
            Authorization: `Bearer ${this.token}`
          },
        }).then(() => {
          this.$message.success("删除成功");
          this.get_cart(); // 重新加载购物车数据
        }).catch(error => {
          console.error('删除失败:', error);
        });
      });
    },
  },
  components: {
    Header,
    Footer,
    CartItem,
  }
};
</script>

<style scoped>

.cart_title {
  margin: 25px 0;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.cart_title .text {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
}

.cart_title .total {
  font-size: 16px;
  color: #666;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
}
.cart_info {
  width: 1200px;
  margin: 0 auto 200px;
}

.cart_table {
  width: 100%;
  margin-top: 20px;
}

.cart_head_row {
  background: #F7F7F7;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 8px 8px 0 0;
}

.cart_course_list {
  margin-top: 10px;
}

.cart_footer_row {
  background: #F7F7F7;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 0 0 8px 8px;
}

.select_all {
  display: flex;
  align-items: center;
}

.total_price {
  font-size: 18px;
  color: #666;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
}

.total_price .price {
  color: #ff6700;
  font-weight: bold;
}

.goto_pay .el-button {
  font-size: 16px;
  font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
}
</style>